/*  This file is a part of JJSched source code
    JJSched - Java Jabber Scheduler - a simple Jabber scheduling application
    Copyright (C) 2008 Cestmir "CZestmyr" Houska

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/> */

package czestmyr.jjsched;

import java.sql.*;

/**
 * Class that handles the periodic sending of planned events
 */
public class Sender{
    public Sender(DatabaseConnector newDbc, Connector newConn){
        dbc = newDbc;
        conn = newConn;
    }

    /**
     * Sends all actual messages to their subscribers.
     *
     * An actual message is a message that has an older timestamp than the current system time.
     */
    public void sendActual(){
        try {
            long time = System.currentTimeMillis();

            //Select all actual user messages
            ResultSet result = dbc.getUserEventsOlderThan(time);
            //For each message, check who it is for, and send it to the receiver
            while (result.next()){
                //Get the needed data
                String jid = result.getString("jabber_id");
                String description = result.getString("description");
                //Send the message
                conn.sendMessage(description, jid);
            }

			//The first result set is not used anymore
			dbc.dropResults();

            //Delete those messages from the DB
            dbc.deleteUserEventsOlderThan(time);

            //Select all actual group messages
            result = dbc.getGroupEventsOlderThan(time);
            //For each message, check who it is for, and send it to the receiver
            while (result.next()){
                //Get the needed data
                String jid = result.getString("jabber_id");
                String description = result.getString("description");
                //Send the message
                conn.sendMessage(description, jid);
            }

			//The first result set is not used anymore
			dbc.dropResults();

            //Delete those messages from the DB
            dbc.deleteGroupEventsOlderThan(time);
        } catch (Exception e) {
            System.err.println("sendActual() exception: "+e.getMessage());
        }
    }

    private DatabaseConnector dbc;
    private Connector conn;
}
